import jwt

from conf import token_conf
from qqmall import settings
from utils.resFormatUyil import FormatResponse


class TokenMiddleWare:
    # 初始化
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request, *args, **kwargs):
        # 处理请求之前执行的代码
        # 获取当前的API信息，是否需要进行token校验
        api = f'{request.method}:{request.path}'
        # 判断当前api是否需要进行token校验
        if api in settings.TOKEN_API:
            # 获取token
            authorization = request.META.get('HTTP_AUTHORIZATION')
            print(authorization)
            # 1.判断是否有token
            if not authorization:
                return FormatResponse(status='ACCESS_RESTRICTION').res()

            # 解析令牌
            try:
                user = jwt.decode(authorization, token_conf.TOKEN_SECRET_KEY, algorithms=token_conf.ALGORITHM)
                # 给request对象增加email属性
                setattr(request, 'email', user.get('data'))
            # 2.判断令牌是否过期
            except jwt.exceptions.ExpiredSignatureError:
                return FormatResponse(status='CODE_EXPIRED').res()
            # 3.判断令牌是否正确
            except jwt.exceptions.DecodeError:
                return FormatResponse(status='PARAM_ERROR').res()
            except Exception:
                return FormatResponse(status='UNKNOWN_ERROR').res()

        # 发送请求获取响应
        response = self.get_response(request)

        # 响应之后的代码
        return response